package dev.alm.cqtakeoutservice.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

public class HttpUtil {

    public static JSONObject doGet(String url) throws IOException {
        CloseableHttpClient client = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse response = client.execute(httpGet);
        HttpEntity responseEntity = response.getEntity();
        if (responseEntity == null) {
            return null;
        }
        String string = EntityUtils.toString(responseEntity);
        JSONObject resObject = JSONObject.parseObject(string);
        return resObject;
    }

    public static JSONObject doPost(String url, JSONObject json) throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type", "application/json");
        StringEntity entity = new StringEntity(json.toJSONString(), "UTF-8");
        httpPost.setEntity(entity);
        CloseableHttpResponse response = httpClient.execute(httpPost);
        HttpEntity responseEntity = response.getEntity();
        if (responseEntity == null) {
            return null;
        }
        String string = EntityUtils.toString(responseEntity);
        JSONObject resObject = JSONObject.parseObject(string);
        response.close();
        httpClient.close();
        return resObject;
    }
}
